package com.tang.lts.core.store;

import com.tang.lts.core.cluster.Config;
import com.tang.lts.core.spi.ServiceLoader;
import com.tang.lts.core.store.datasource.DataSourceProvider;

import javax.sql.DataSource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Tang
 * @classname SqlTemplateFactory
 * @description [  ]
 * @date 2022/5/6 14:31
 */
public class SqlTemplateFactory {

    private static ConcurrentHashMap<DataSource, SqlTemplate> HOLDER = new ConcurrentHashMap<>();

    public static SqlTemplate getSqlTemplate(Config config) {
        DataSourceProvider dataSourceProvider = ServiceLoader.loadDefault(DataSourceProvider.class);
        DataSource dataSource = dataSourceProvider.getDataSource(config);
        SqlTemplate sqlTemplate = HOLDER.get(dataSource);
        if (sqlTemplate != null) {
            return sqlTemplate;
        }else {
            sqlTemplate = new SqlTemplateImpl(dataSource);
            HOLDER.put(dataSource, sqlTemplate);
        }
        return sqlTemplate;
    }

}